const Service = require('egg').Service;
const _ = require('underscore');

class OrgService extends Service {

  async create(org) {
    const lastOrgId = await this.app.mysql.query(`SELECT MAX(id) FROM org;`);
    const orgCreate = { ...org, id: lastOrgId[0]['MAX(id)'] + 1, sortId: (lastOrgId[0]['MAX(id)'] + 1) % 100 };
    const result = await this.app.mysql.insert('org', orgCreate);

 if (result.affectedRows === 1) {
     const updateOrganizationTreeResult = await this.app.mysql.query('CALL updateOrgTree(1);');
     const updateMemberTreeResult = await this.app.mysql.query('CALL updateMemberTree();');
     const updateCountResult = await this.app.mysql.query('CALL updateOrgCount();');
    }

    return result;
  }

  async update(org) {
    const result = await  this.app.mysql.update('org', org)

    if (result.affectedRows === 1) {
     const updateOrganizationTreeResult = await this.app.mysql.query('CALL updateOrgTree(1);');
     const updateMemberTreeResult = await this.app.mysql.query('CALL updateMemberTree();');
     const updateCountResult = await this.app.mysql.query('CALL updateOrgCount();');
    }

    return result;

    }   

}

module.exports = OrgService;
